<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="refreshChange"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel">
        <template slot="menuLeft">
          <el-button type="primary" icon="el-icon-plus" @click="addDocNo">添加工单</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text"  icon="el-icon-delete"  size="small" plain  @click="handleDel(scope.row,scope.index)">删除</el-button>
        </template>
      </avue-crud>
      <!--新增排产工单页面-->
      <el-dialog title=""
                 :visible.sync="addDocNoDialogVisible"
                 width="50%"
                 lock-scroll
                 append-to-body
                 v-if="addDocNoDialogVisible"
                 :close-on-click-modal="false"
                 :fullscreen="addDocNoDialogFull">
        <template slot="title">
          <div class="avue-crud__dialog__header">
              <span class="el-dialog__title">
                  <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                  添加工单
              </span>
          </div>
        </template>
        <el-main>
          <el-form ref="form" :model="form" label-width="140px" :rules="rules">
            <el-form-item label="添加工单：" prop="workOrderId" >
              <el-select v-model="form.workOrderId" placeholder="添加工单"  multiple filterable  style="width:80%;">
                <el-option
                  v-for="item in docNoList"
                  @click.native="checkDocNo(item)"
                  :key="item.id"
                  :label="`【工单号：`+item.docNo+`】【品号：`+item.itemCode+`】` "
                  :value="item.id">
                  <span style="float: left">工单号：{{ item.docNo }}</span>
                  <span style=" color: #5e80a6; font-size: 13px">品号：{{ item.itemCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <div style="margin-top: 35px;text-align: -webkit-center">
              <el-button type="primary" @click="saveScheduleDocNo">保存</el-button>
              <el-button @click="closeAddDocNo">取消</el-button>
            </div>
          </el-form>
        </el-main>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {fetchList, addObj, putObj, delObj, saveDocNo,getDocNoStr} from '@/api/workorder/workscheduling'
import { getDocNoByLineIdAndItemCode} from '@/api/workorder/workordercps' //获取所有工单信息
import { tableOption } from '@/const/crud/workorder/workscheduling'
import { mapGetters } from 'vuex'
import {saveRealityLine} from "@/api/pfoc/realityproductline";

export default {
  name: 'workscheduling',
  props:{
    planTime:{//排产时间
      type: String
    },
    scheduleId:{//排产ID
      type: String
    },
    workshopId:{//车间ID
      type: String
    },
    workshopName:{//车间名
      type: String
    },
    productionLineId:{//产线ID
      type: String
    },
    productionLineName:{//产线名称
      type: String
    },
  },
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      addDocNoDialogVisible:false,//新增排产页面开关
      addDocNoDialogFull:false,//新增排产页面弹窗缩放开关（默认放大）
      docNoList:[],//当前排产车间产线下可生产品号对应的工单集合
      form:{
        workOrderId:[],//工单ID集合
      },
      rules: {
        workOrderId: [
          { type: 'array', required: true, message: '请至少选择一个工单',trigger: ['blur', 'change']}
        ]
      },

      docNoStr:[],//排产选择字的工单号符串用于判断产线下所选排工单号是否重复
    }
  },

  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.workorder_workscheduling_add, false),
        delBtn: this.vaildData(this.permissions.workorder_workscheduling_del, false),
        editBtn: this.vaildData(this.permissions.workorder_workscheduling_edit, false)
      }
    }
  },
  mounted() {
    //根据产线Id获取产线下可生产产品品号并根据品号去工单表查询可生产工单
    this.getDocNoByLineIdAndItemCodeData();
    //获取当前排产中可生产的工单号集合
    this.getDocNoStrData();

  },
  methods: {
    // 列表查询
    getList(page, params) {
      this.tableLoading = true
      this.searchForm.scheduleId = this.scheduleId;//排产ID
      fetchList(Object.assign({
        descs:"create_time",
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
        //刷新工单号集合
        this.getDocNoStrData();
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    //根据产线Id获取产线下可生产产品品号并根据品号去工单表查询可生产工单
    getDocNoByLineIdAndItemCodeData(){
      getDocNoByLineIdAndItemCode(this.productionLineId).then(response => {
        this.docNoList=response.data.data;
      })
    },
    //获取当前排产中可生产的工单号集合
    getDocNoStrData(){
     getDocNoStr(this.scheduleId).then(response => {
        this.docNoStr=response.data.data;
      })
    },

    //校验当前选择工单是否重复
    checkDocNo(row){
      if(this.form.workOrderId.includes(row.id)) { //不包含则为取消操作
        if (this.docNoStr.includes(row.docNo)) {//产线可生产工单号
          this.$message.error("已存在所选工单");
          const index = this.form.workOrderId.indexOf(row.id);//获取当前选择选项位置
          if (index !== -1) {
            this.form.workOrderId.splice(index, 1);//删除当前选项
          }
        }
      }/*else {//不存在所选择的工单ID则在工单集合中去掉工单号
        const index = this.docNoStr.indexOf(row.docNo);//获取当前选择选项位置
        if (index !== -1) {
          this.docNoStr.splice(index, 1);//删除当前选项
        }
      }*/
    },
    //保存排产工单
    saveScheduleDocNo(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var data={
            scheduleId:this.scheduleId,//排产ID
            productionLineId:this.productionLineId,//产线ID
            productionLineName:this.productionLineName,//产线名称
            planTime:this.planTime,//排产时间
            workshopId:this.workshopId,//车间ID
            workshopName:this.workshopName,//车间名
            workOrderIdArr:this.form.workOrderId,//工单ID集合
          }
          //提交
          saveDocNo(data).then(response => {
            if(response.data.data.length>0) {
              this.$message.warning(
                {
                  message: "添加成功，其中工单："+response.data.data+"等已排产，已忽略重复添加",
                  duration: 5000 // 设置时长为5秒
                });
            }else{
              this.$message.success("保存成功。")
            }
            this.closeAddDocNo();//关闭新增页面
          });
        } else {
          return false;
        }
      });
    },

    //新增排产
    addDocNo(){
      //每次打开前清空之前所选
      this.form.workOrderId =[];
      //打开新增排产页面
      this.addDocNoDialogVisible = true;
    },
    //关闭新增排产弹窗
    closeAddDocNo(){
      //关闭新增排产页面
      this.addDocNoDialogVisible = false;
      //刷新列表
      this.refreshChange();
      //刷新工单号集合
      this.getDocNoStrData();
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/workorder/workscheduling/export', this.searchForm, 'workscheduling.xlsx')
    }
  }
}
</script>
